package com.shop.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.shop.exception.zdyException;
import com.shop.po.User;
import com.shop.service.UserService;

@Controller
public class findpswController {

	@Autowired
	private UserService userService;

	@RequestMapping("findpsw")
	public String findpsw() {
		return "findpsw";
	}

	@RequestMapping("/findQuestionByUsername")
	public String activeUser(HttpServletRequest request, @RequestParam String checkImg,@RequestParam String username, Model model) throws zdyException, Exception {
		String sessionCode = (String) request.getSession().getAttribute("checkcode");
		if (!sessionCode.equalsIgnoreCase(checkImg)) {
			// model.addAttribute("message", "验证码输入错误请重新注册");
			// throw new zdyException("验证码输入错误请重新注册");
			request.getSession().setAttribute("messageUser", "验证码输入错误请重新注册");
			return "redirect:findpsw.action";
		}
		User user = userService.selectByUsername(username);
		if (user != null) {
			model.addAttribute("user", user);
			return "question";
		}
		model.addAttribute("messageUser", "用户名不存在,请重新输入!");
		return "findpsw";
	}

	@RequestMapping("/checkAnswer")
	public String checkAnswer(@RequestParam String username, @RequestParam String question, @RequestParam String answer,
			Model model) {
		User user = userService.selectByUsernameAndQuestion(username, question);
		model.addAttribute("user", user);
		if (answer.equals(user.getAnswer())) {
			return "updatePsw";
		} else {
			model.addAttribute("messageAnswer", "密保答案错误,请重新输入!");
			return "question";
		}
	}

	@RequestMapping("/updatePsw")
	public String updatePsw(@RequestParam String checkImg,HttpServletRequest request,@RequestParam String username, @RequestParam String password,
			@RequestParam String rePassword, Model model) throws Exception {
		User user = userService.selectByUsername(username);
		model.addAttribute("user", user);
		String sessionCode = (String) request.getSession().getAttribute("checkcode");
		
		if (!password.equals(rePassword)) {
			request.setAttribute("messagePsw", "两次密码不一致,请重新输入!");
			return "updatePsw";
		} 
		request.setAttribute("passwordInfo", password);
		request.setAttribute("rePasswordInfo", rePassword);
		model.addAttribute("user", user);
		if (!sessionCode.equalsIgnoreCase(checkImg)) {
			// model.addAttribute("message", "验证码输入错误请重新注册");
			// throw new zdyException("验证码输入错误请重新注册");
			request.getSession().setAttribute("messagePsw", "验证码输入错误请重新输入!");
			return "updatePsw";
		}
		else {
			userService.updatePsw(username, password);
			request.setAttribute("message", "密码修改成功,请前去登录!");
			return "msg";
		}
	}
	
	
}
